package com.jorkyin.waterdrop.base;

import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;

public abstract class BaseListener<T> {
    public void onComplete() {}

    public void onError(int code) {}

    public abstract void onNext(T t);

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            if (message.what == 0) {
                onComplete();
            }else if (message.what == 1) {
                onError((Integer) message.obj);
            } else if (message.what == 2) {
                onNext((T) message.obj);
            }
            return false;
        }
    });

    public void postonComplete() {
        Message message = new Message();
        message.what = 0;
        handler.sendMessage(message);
    }

    public void postonError(int code) {
        Message message = new Message();
        message.what = 1;
        message.obj = code;
        handler.sendMessage(message);
    }

    public void postNext(T t) {
        Message message = new Message();
        message.what = 2;
        message.obj = t;
        handler.sendMessage(message);
    }
}